import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Home from '@/views/layout/home.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
import Category from '@/views/layout/category'
const login = () => import('@/views/login')
const Search = () => import('@/views/search')
const ProDetail = () => import('@/views/prodetail')
const Pay = () => import('@/views/pay')
const MyOrder = () => import('@/views/myorder')
const SearchList = () => import('@/views/search/list.vue')
const store = () => import('@/store')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: login },
    {
      path: '/',
      component: Layout,
      children: [
        { path: '/home', component: Home },
        { path: '/cart', component: Cart },
        { path: '/user', component: User },
        { path: '/category', component: Category },
        { path: '/', redirect: '/home' }
      ]
    },
    { path: '/search', component: Search },
    { path: '/prodetail/:id', component: ProDetail },
    { path: '/searchlist', component: SearchList },
    { path: '/pay', component: Pay },
    { path: '/myorder', component: MyOrder }
  ]
})
// 所有的路由在真正被访问到之前(解析渲染对应组件页面前)，都会先经过全局前置守卫
// to: 到哪里去，到哪去的完整路由对象
// from: 从哪里来，从哪来的完整路由对象
// next(): 是否放行
// next(): 放行
// next(路径) 进行拦截，拦截到next里面配置的路径
const autoUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  console.log(to, from, next)
  // 看to.path是否在autoUrls里面
  if (!autoUrls.includes(to.path)) {
    next()
    return
  }
  const token = store.getters.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})
export default router
